package view;

import Dao.Blog;
import Dao.BlogDao;
import Dao.User;
import common.Util;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebListener;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/index.html")
public class indexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        User user = Util.checkLoginStatus(req);
        if(user == null){
            System.out.println("当前未登录");
            resp.sendRedirect("login.html");
            return;
        }

        // 1. 从数据库中 拿到 所有的博客列表
        BlogDao blogDao = new BlogDao();
        List<Blog> blogs = blogDao.selectAll();
        // 2. 通过模板引擎渲染页面
        TemplateEngine engine =(TemplateEngine) getServletContext().getAttribute("engine");
        WebContext webContext = new WebContext(req,resp,getServletContext());
        webContext.setVariable("blogs",blogs);
        webContext.setVariable("num",blogDao.selectTotal(user.getUserId()));
        webContext.setVariable("user",user);
        engine.process("index",webContext,resp.getWriter());
    }
}
